<template>
  <el-dialog
    @open="getRoleInfo()"
    :title="viewStatus ? '添加角色' : '修改角色'"
    @close="aditClosed"
    :visible.sync="dialogVisible"
    width="750px"
  >
    <el-form
      :model="roleInfo"
      :rules="rules"
      ref="RuleForm"
      label-width="100px"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleInfo.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="roleInfo.roleDesc"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="viewStatus ? addtRoleInfo() : changeRoleInfo()"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { UserInfoRules } from '@/common/mixin'
import {
  addtRoleInfoApi,
  changeRoleInfoApi,
  getRoleInfoApi
} from '@/Utils/Api/getUserRightApi'
export default {
  name: 'addUserRoles',
  mixins: [UserInfoRules],
  data () {
    return {
      dialogVisible: false,
      viewStatus: false,
      roleInfo: {
        roleName: '',
        roleDesc: ''
      },
      roleId: ''
    }
  },
  components: {},
  created () {},
  mounted () {},
  methods: {
    // 获得
    async getRoleInfo () {
      if (this.viewStatus) {
        return
      }
      const { data } = await getRoleInfoApi(this.roleId)
      this.roleInfo = data.data
    },
    // 修改
    async changeRoleInfo () {
      this.$refs.RuleForm.validate(async (vail) => {
        if (!vail) return
        const { data } = await changeRoleInfoApi(this.roleId, this.roleInfo)
        if (data.meta.status !== 200) {
          return this.$message({
            type: 'error',
            message: data.meta.msg
          })
        }
        this.$emit('getRoleInfoDrive')
        this.$message({
          type: 'success',
          message: data.meta.msg
        })
        this.dialogVisible = false
      })
    },
    // 添加
    addtRoleInfo () {
      this.$refs.RuleForm.validate(async (vail) => {
        if (!vail) return
        try {
          const { data } = await addtRoleInfoApi(this.roleInfo)
          if (data.meta.status === 201) {
            // 重新获取列表,刷新视图
            this.$emit('getRoleInfoDrive')
            this.dialogVisible = false
            return this.$message({
              type: 'success',
              message: data.meta.msg
            })
          } else {
            this.$message({
              type: 'error',
              message: data.meta.msg
            })
          }
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 关闭窗口后清空表单
    aditClosed () {
      this.$refs.RuleForm.resetFields()
    }
  },
  computed: {},
  watch: {}
}
</script>

<style scoped>
</style>
